package com.teama4.shop.controller;


import com.teama4.shop.annotation.NeedLogin;
import com.teama4.shop.domain.*;
import com.teama4.shop.service.*;
import com.teama4.shop.utils.CommodityRecommendationUtils;
import com.teama4.shop.utils.FileUtil;
import com.teama4.shop.utils.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/evaluate")
public class EvaluateController {

    @Autowired
    private EvaluateService evaluateService;

    @Autowired
    private EvaluatePicService evaluatePicService;

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private CommodityOrdersService commodityOrdersService;

    @Autowired
    private SpecificationService specificationService;


    /**
     * 判断是否已经评价
     *
     * @param orderId
     * @param specificationId
     * @return
     */

    private boolean isHavaEva(Integer userId, Integer orderId, Integer specificationId) {

        EvaluateExample evaluateExample = new EvaluateExample();
        evaluateExample.createCriteria().andOrderIdEqualTo(orderId)
                .andSpecificationIdEqualTo(specificationId)
                .andUserIdEqualTo(userId);

        List<Evaluate> evaluates = evaluateService.selectByExample(evaluateExample);
        if(evaluates.size()>0){
            return true;
        }
        return false;

    }

    @NeedLogin
    @RequestMapping("addEvaluate")
    public void addEvaluate(HttpServletRequest req, HttpServletResponse resp, Model model, Integer evaScore, String describe, Integer anonymous, Integer orderId, Integer specificationId,String fileName) {
        HttpSession session = req.getSession(false);
        if (session != null && session.getAttribute("userId") != null) {
            Integer userId = (Integer) session.getAttribute("userId");
            String[] fileNames = fileName.split(",");
            if (!isHavaEva(userId,orderId,specificationId)) {
                Evaluate evaluate = new Evaluate();
                evaluate.setUserId(userId);
                evaluate.setContent(describe);
                evaluate.setOrderId(orderId);
                evaluate.setSpecificationId(specificationId);

                Specification specification = specificationService.selectByPrimaryKey(specificationId);
                if (specification != null) {
                    evaluate.setCommodityId(specification.getCommodityId());
                }

                evaluate.setLikeCount(0);
                evaluate.setEvaScore(evaScore);
                evaluate.setAnonymous(anonymous);
                Date date = new Date();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd :HH:mm:ss");
                evaluate.setEvaluateDate(dateFormat.format(date));
                int res = evaluateService.insertSelective(evaluate);


                EvaluateUserSpeComExt evaluateUserSpeComExt = evaluateService.selectEvaluateByUserSpeId(userId, orderId, specificationId);


                for (int i=0;i<fileNames.length;i++){
                    EvaluatePic evaluatePic = new EvaluatePic();
                    evaluatePic.setEvaluateId(evaluateUserSpeComExt.getEvaluateId());
                    evaluatePic.setPicture(fileNames[i]);
                    evaluatePicService.insertSelective(evaluatePic);

                }

                if (res > 0) {
                    //如果插入成功
                    HashMap<String, Object> map = new HashMap<String, Object>();
                    map.put("result", "ok");
                    JSONUtil.printByJSON(resp, map);
                    //生成用户推荐
                    new CommodityRecommendationUtils().recommend(userId);
                } else {
                    for (int i=0;i<fileNames.length;i++){
                        FileUtil.delFile("/myFile/img/evaluatePic/"+fileNames[i]);
                    }
                    //如果插入失败
                    HashMap<String, Object> map = new HashMap<String, Object>();
                    map.put("result", "fail");
                    JSONUtil.printByJSON(resp, map);
                }

            } else {
                for (int i=0;i<fileNames.length;i++){
                    FileUtil.delFile("/myFile/img/evaluatePic/"+fileNames[i]);
                }
                HashMap<String, Object> map = new HashMap<String, Object>();

                map.put("result", "had");
                JSONUtil.printByJSON(resp, map);
            }
        }else {
            //如果session获取不到值
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("result", "noSession");
            JSONUtil.printByJSON(resp, map);
        }
    }
}
